import {Component, Input, OnInit, ViewChild} from '@angular/core';
import {InvokeResultDto} from '../../entity/invoke-result-dto';
import {JsonEditorComponent, JsonEditorOptions} from 'ang-jsoneditor';
import {EntityRef} from '../../entity/entity-ref';
import {DocService} from '../../service/doc.service';
import {EntityUtils} from '../../utils/entity-utils';

@Component({
    selector: 'app-invoke-response',
    templateUrl: './invoke-response.component.html',
    styleUrls: ['./invoke-response.component.css']
})
export class InvokeResponseComponent implements OnInit {

    activeResponseTab = 'bodyJson';

    _invokeResult: InvokeResultDto;

    responseBody: any;

    jsonEditorOptions: JsonEditorOptions;

    @ViewChild('jsonView') editor: JsonEditorComponent;

    constructor(private docService: DocService) {
        this.jsonEditorOptions = new JsonEditorOptions();
        this.jsonEditorOptions.indentation = 4;
        this.jsonEditorOptions.mode = 'tree';
        this.jsonEditorOptions.statusBar = false;
    }

    ngOnInit() {
    }

    @Input()
    set invokeResult(invokeResult: InvokeResultDto) {
        this._invokeResult = invokeResult;
        if (invokeResult.status === 200) {
            const body = invokeResult.responseBody;
            if (body) {
                if (body[0] === '[' || body[0] === '{') {
                    this.responseBody = JSON.parse(body);
                } else {
                    this.responseBody = body;
                }
            }
        } else {
            this.activeResponseTab = 'body';
        }
    }

    get invokeResult() {
        return this._invokeResult;
    }

    setTab(tabName: string) {
        this.activeResponseTab = tabName;
    }
}
